/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package crawler.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author LT
 */
public class DateUtil {
    public static List<String> dateFormat = new LinkedList<>();
    public static List<String> timeFormat = new LinkedList<>();
    private static final DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy H:m");
    public static void main(String[] args){
        initPattern();
     //   parseDate("thu hai 12/09/2012 luc 12 gio");
        //parseDate("thu hai 12-09-2012 luc 12 gio");
        String vnexpress = "Thứ ba, 18/11/2014 | 04:28 GMT+7";
        String bongdaComVn = "3:20 18/11/2014";
        String bongdaComVn2 = "20:16 19/5/2014";
        String bongdaso = "Thứ ba, 18/11/2014 00:02";
        parseDate(bongdaso);
    }
    private static void initPattern(){
        dateFormat.add("\\d+/\\d+/\\d+");
        dateFormat.add("\\d+\\-\\d+\\-\\d+");
        timeFormat.add("\\d+:\\d+");
    }
    public static long parseDate(String input){
        initPattern();
        long output = 0;
        String dateStr = "";
        for (String item : dateFormat) {
            Pattern p1 = Pattern.compile(item);
            Matcher m1 = p1.matcher(input);
            while (m1.find()) {
                String tmp = m1.group(0);
                dateStr = tmp;
            }
        }
        for (String item : timeFormat) {
            Pattern p2 = Pattern.compile(item);
            Matcher m2 = p2.matcher(input);
            while (m2.find()) {
                String tmp = m2.group(0);
                dateStr += " " + tmp;
            }
        }
        try {
            Date date;
            date = formatter.parse(dateStr);
            output = date.getTime()/1000L;
            if(input.contains("PM") || input.contains("pm")){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
                if(hourOfDay < 12){
                    output = output + 3600 * 12;
                }
            }

        } catch (ParseException ex) {
            Logger.getLogger(DateUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return output;
    }
}
